﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Micro.Core.ApiConsumer.Enums;

namespace Micro.Core.ApiConsumer.ActionAttributes
{
    public sealed class RequestMapping : ApiActionAttribute
    {
        /// <summary>
        /// 接口路由地址
        /// </summary>
        public string Value { get; set; }

        /// <summary>
        /// 特性索引
        /// </summary>

        public override int OrderIndex { get => Int32.MinValue + 1; }

        /// <summary>
        /// http请求方式
        /// </summary>
        public RequestMethod Method { get; set; }

        public RequestMapping()
        {
            Method = RequestMethod.GET;
        }

        /// <summary>
        /// 组装接口属性
        /// </summary>
        /// <param name="request"></param>
        public override void Compose(HttpRequest request)
        {
            // 组装host
            var baseUrl = request.Url;
            if(baseUrl == null)
            {
                throw new Exception("接口Host地址或者对应服务名必须配置!");
            }
            if (Value == null)
            {
                throw new Exception("接口路由地址必须配置!");
            }
            request.Url = new Uri(baseUrl, Value);

            // 组装method
            request.Method = GetMethod(Method);
        }

        /// <summary>
        /// 获取http请求方式
        /// </summary>
        /// <param name="method">http请求方式枚举</param>
        /// <returns></returns>
        private string GetMethod(RequestMethod method)
        {
            var methodStr = String.Empty;
            switch (method)
            {
                case RequestMethod.GET:
                    methodStr = "GET";
                    break;
                case RequestMethod.POST:
                    methodStr = "POST";
                    break;
                case RequestMethod.PUT:
                    methodStr = "PUT";
                    break;
                case RequestMethod.DELETE:
                    methodStr = "DELETE";
                    break;
                default:
                    methodStr = "GET";
                    break;
            }
            return methodStr;
        }
    }
}
